//
//  AddCityViewController.m
//  Sky
//
//  Created by chenheren on 16/7/10.
//  Copyright © 2016年 chen. All rights reserved.
//

#import "AddCityViewController.h"
#import "MatchingCitiyListCell.h"
#import "AFNetworking.h"

@interface AddCityViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>

@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *cities;
@property (strong, nonatomic) NSMutableArray *matchingCities;

@end

static NSString *MatchingTableCellIdentifier = @"MatchingTableCellIdentifier";

@implementation AddCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.matchingCities = [[NSMutableArray alloc]init];
    self.cities = [[NSMutableArray alloc]init];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"AllCities.plist"];
    if ([[NSFileManager defaultManager]fileExistsAtPath:filePath] == YES) {/////
        NSLog(@"AllCities.plist is exist,loading");
        NSDictionary *dataDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
        [self loadCityList:dataDic];
    }else{
        [self fetchCityList];
    }
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MatchingCitiyListCell" bundle:nil] forCellReuseIdentifier:MatchingTableCellIdentifier];
    
  //  [self.tableView addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(matchingCityName:) name:UITextFieldTextDidChangeNotification object:self.textField];
}

-(void)loadCityList:(NSDictionary *)dataDic{
    if (dataDic == nil) {
        return;
    }
    
    NSArray *cityInfoArray = [dataDic objectForKey:@"city_info"];
    [cityInfoArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *cityDic = cityInfoArray[idx];
        [self.cities addObject:[cityDic objectForKey:@"city"]];
        
    }];
    
    NSLog(@"城市列表记载完成: %@",dataDic);
}

-(void)fetchCityList
{
    /**************************拉取城市列表************************************/
    
    NSString *key=@"06bd70e97b144a8eb6f77880f25ce64a";
    NSString *urlString = @"https://api.heweather.com/x3/citylist";
    NSDictionary *parameter = @{@"search":@"allchina",
                                @"key":key};
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.requestSerializer.timeoutInterval = 10.0;
    [manage GET:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil && [[responseObject objectForKey:@"status"] isEqualToString: @"ok"]) {
            NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:responseObject];
            NSString *filePath= [ NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"AllCities.plist"];
            [dataDic writeToFile:filePath atomically:YES];
            [self loadCityList:dataDic];
            NSLog(@"获取成功");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络错误");
    }];
    
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"text"]) {
        [self matchingCityName:self.textField.text];
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self matchingCityName:textField.text];
}

-(void)matchingCityName:(NSString*)cityName{
    //重新匹配前清空原来匹配的数组
    [self.matchingCities removeAllObjects];
    
    for (NSString *city in self.cities) {
        
        if ([city rangeOfString:cityName].location != NSNotFound) {
            [self.matchingCities addObject:city];
        }
    }
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.matchingCities.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MatchingCitiyListCell *cell = (MatchingCitiyListCell *)[tableView dequeueReusableCellWithIdentifier:MatchingTableCellIdentifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[MatchingCitiyListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MatchingTableCellIdentifier];
    }
    cell.cityNameLabel.text = self.matchingCities[indexPath.row];
    return cell;
}

#pragma mark - UITableViewdelegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIAlertView *alert = [[UIAlertView alloc]init];
    alert.title = @"提示";
    alert.message = [NSString stringWithFormat:@"添加城市:%@",self.textField.text];
    alert.delegate =self;
    [alert addButtonWithTitle:@"取消"];
    [alert addButtonWithTitle:@"确定"];
    alert.cancelButtonIndex =0;
    [alert show];
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        NSString *filePath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"SelectedCities.plist"];
        NSMutableArray *cities = [NSMutableArray arrayWithContentsOfFile:filePath];
        NSUInteger selectedIndex = [self.tableView indexPathForSelectedRow].row;
        //若原来列表没有才需要存储
        if ([cities indexOfObject:self.matchingCities[selectedIndex]] == NSNotFound) {
            [cities addObject:self.matchingCities[selectedIndex]];
            [cities writeToFile:filePath atomically:YES];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"CityListDidChanged" object:nil];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}



@end
